<?php
namespace App\Admin\Controllers\Inventory;

use App\Admin\Ajax\Inventory\SplitAjax;
use App\Admin\Controllers\ErpController;
use App\Models\Inventory\PublicCn;
use App\Models\Inventory\Timely;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductMixSku;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use Illuminate\Support\Facades\Request;
class SplitController extends ErpController {

    protected $title = '库存拆分';

    protected $filters = [
        'sku' => null,
        'classify_id' => null,
    ];

    protected function grid()
    {
        $filters = $this->getFilters();
        $this->initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->paginator($query);
        $action = $this->getAction();
        $filtersBlade = [];
        $filtersBlade['sku'] = $this->filters['sku'];
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $downloadUrl = '/xqc/inventory/split-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('inventory.split.index', compact('paginator','filtersBlade','action','downloadUrl'));
    }

    private function _initQuery($filters){
        $query = ProductSku::query()
            ->where('is_mix',1)
            ->orderBy('id','DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'sku'){
                $query->where(function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'classify_id'){
                $query->where('classify_id', $filter);
            }
        }
        return $query;
    }

    public function download(){
        $filters = $this->getFilters();
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['SKU','关联SKU','品类','总库存','PUBLIC库存','可拆分数量','产品名称'];
        RExcel::exportCsv("库存拆分",function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(800, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
    }

    protected static function getDownloadData($re){
        foreach ($re as $row){
            $mixRuleArr = ProductMixSku::_mixRuleArrIDAsKey($row->mix_rule);
            $temp = [];
            $temp['psku_code'] = $row->psku_code;
            $temp['re_psku_code'] = '';
            $temp['title'] = ProductClassify::getTitleById($row->classify_id);
            $temp['instant'] = Timely::getInstant($row->id);
            $temp['p_instant'] = PublicCn::getInstant($row->id);
            $temp['split_num'] = $temp['p_instant'];
            $temp['psku_cn'] = $row->psku_cn;
            yield $temp;
            $cSku = self::getMixInventory($mixRuleArr);
            foreach($cSku as $item){
                $temp = [];
                $temp['psku_code'] = $row->psku_code;
                $temp['re_psku_code'] = $item['sku'];
                $temp['title'] = $item['title'];
                $temp['instant'] = '';
                $temp['p_instant'] = $item['p_instant'];
                $temp['split_num'] = '';
                $temp['psku_cn'] = $item['sku_cn'];
                yield $temp;
            }
        }
    }

    public static function getMixInventory($mixRuleArr){
        $re = [];
        foreach ($mixRuleArr as $pSkuId => $num){
            $ps = ProductSku::getModelById($pSkuId);
            $re[$pSkuId]['sku'] = $ps->psku_code.' x '.intval($num);
            $re[$pSkuId]['p_instant'] = PublicCn::getInstant($pSkuId);
            $re[$pSkuId]['title'] = $ps->classify->title ?? '';
            $re[$pSkuId]['sku_cn'] = $ps->psku_cn;
        }
        return $re;
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new SplitAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }
}
